<template>
	<view>
		<web-view :src="websrc" @message='handleMessageMessage'></web-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				pages: '/hybrid/html/index.html',
				websrc: '',
				socketTask: '', //socket对象
				id: '',
				name: '',
				roomid: '1001',
				isMyCollRemote: false, //自己是否为呼叫发起方
				offer: null,
				answer:null,
				mainFrame: '',
				wv: '',
				postMsg: () => {} //注册方法用于uniapp向webview发送消息
			}
		},
		onLoad(e) {
			if (window) {
				window.addEventListener("message", this.handleMessageMessage, false);
			}
			this.id = e.id
			this.name = e.name
			this.websrc = `${this.pages}?id=${this.id}&name=${this.name}`
			this.initWebSocket()
		},
		onReady() {
			// #ifdef H5
			setTimeout(() => {
				let Frames = document.getElementsByTagName('iframe');
				this.mainFrame = Frames[0].contentWindow;
				this.postMsg = this.h5sendH5
			}, 500)
			// #endif

			// #ifdef APP-PLUS
			var currentWebview = this.$scope.$getAppWebview()
			setTimeout(() => {
				this.wv = currentWebview.children()[0]
				this.postMsg = this.appsendH5
			}, 300);
			// #endif
		},
		methods: {
			//初始化Socket
			initWebSocket() {
				const socketTask = uni.connectSocket({
					url: 'wss://testcall.shengtucuican.com:9999/', // 替换为实际服务器地址
					success: (res) => {
						console.log('WebSocket连接创建成功')
					},
					fail: (err) => {
						console.error('WebSocket连接创建失败：', err)
					}
				});
				// 保存socketTask以便后续操作
				this.socketTask = socketTask;
				this.bindSocketEvents()
			},
			//绑定Socket事件
			bindSocketEvents(socketTask) {
				thissocketTask.onOpen((res) => {
					console.log('WebSocket连接打开', res);
					this.socketTask.send({
						data: JSON.stringify({
							code: 'joinRoom',
							data: this.roomid
						})
					})
				});
				this.socketTask.onMessage((res) => {
					this.socketEmit(res.data)
					// 在这里处理接收到的消息
				});
				this.socketTask.onError((err) => {
					console.error('WebSocket错误：', err);
				});
				this.socketTask.onClose((res) => {
					console.log('WebSocket连接关闭', res);
				});
			},
			//处理事件数据
			socketEmit(message) {
				let data = JSON.parse(message)
				// console.log('data', data);
				switch (data.code) {
					//连接成功
					case 'repConnect':
						console.log(data.data, '连接成功')
						break;
						//连接成功
					case 'repJoinRoom':
						console.log(data.data, '连接成功')
						break;
						//呼叫事件
					case 'repCollRemote':
						this.handleCollRemote(data.data)
						break;
						//呼叫被接通
					case 'repAcceptCall':
						this.handleAcceptCall(data.data)
						break;
						//收到offer
					case 'repSendOffer':
						
						if(!this.isMyCollRemote){
							console.log('3333323232')
							this.postMsg({
								action: 'repSendOffer',
								data:btoa(data.data),
							})
						}
						break;
					case 'repSendAnswer':
						if(this.isMyCollRemote){
							this.postMsg({
								action: 'repSendAnswer',
								data:btoa(data.data),
							})
						}
						break;
					case 'repSendCandidate':
						this.postMsg({
							action: 'repSendCandidate',
							data:btoa(data.data),
						})
						break;
				}
			},
			//处理被呼叫事件
			handleCollRemote(data) {
				if (!this.isMyCollRemote) {
					console.log('正在呼叫我');
					this.websrc = `${this.pages}?id=${this.id}&name=${this.name}&status=1`
				}
			},
			//处理呼叫被接听
			handleAcceptCall() {
				if (this.isMyCollRemote) {
					console.log('呼叫被接听')
					this.socketTask.send({
						data: JSON.stringify({
							code: 'sendOffer',
							data: this.roomid,
							offer: this.offer
						})
					})
				}
			},
			//APP/H5处理来自网页事件  
			handleMessageMessage(e) {
				//兼容H5 APP 来源数据结构
				let data = e?.detail?.data?.[0] ? e.detail.data[0] : e?.data?.data?.arg
				switch (data.action) {
					// 呼叫事件
					case 'call':
						//获取来自webRTC的offer
						console.log('data.data.offer', data)
						this.offer = data.data.offer
						//发起呼叫请求
						this.socketTask.send({
							data: JSON.stringify({
								code: 'collRemote',
								data: this.roomid
							})
						})
						//修改页面状态
						this.isMyCollRemote = true
						break;
					//发送Answer
					case 'sendAnswer':
						//获取来自webRTC的offer
						console.log('data.data.answer', data)
						this.answer = data.data.answer
						//发起呼叫请求
						this.socketTask.send({
							data: JSON.stringify({
								code: 'sendAnswer',
								data: this.roomid,
								answer:this.answer
							})
						})
						break;
					//接听通话
					case 'acceptCall':
					console.log('3333')
						this.socketTask.send({
							data: JSON.stringify({
								code: 'acceptCall',
								data: this.roomid,
							})
						})
						break;
					//呼叫方发送Candidate
					case 'sendCandidate':
						this.socketTask.send({
							data: JSON.stringify({
								code: 'sendCandidate',
								data: this.roomid,
								candidate:data.data.candidate
							})
						})
						break;
				}
			},
			//app与webView通信
			appsendH5(params) {
				console.log('333','params',params);
				this.wv.evalJS("getUniAppMessage('" + JSON.stringify(params) + "')")
			},
			//web与webView通信
			h5sendH5(params) {
				this.mainFrame.postMessage(params, '*')
			},
		}
	}
</script>
<style>

</style>